import axios from 'axios';
import { Environment } from '@/environments/environment.ts';


/**
 * 拦截器
 *
 * @export
 * @class Interceptors
 */
export class Interceptors {

    /**
     * 路由对象
     *
     * @private
     * @type {*}
     * @memberof Interceptors
     */
    private router: any

    /**
     * 拦截器实现接口
     *
     * @private
     * @memberof Interceptors
     */
    private intercept(): void {
        axios.interceptors.request.use((config: any) => {
            let appdata = null;
            if (!Object.is(appdata, '')) {
                config.headers.srfappdata = appdata;
            }
            if (window.localStorage.getItem('srfloginkey')) {
                const token = window.localStorage.getItem('srfloginkey');
                config.headers.Authorization = `Bearer ${token}`;
            }
            if (!config.url.startsWith('https://') && !config.url.startsWith('http://')) {
                config.url = Environment.BaseUrl + config.url;
            }
            return config;
        }, (error: any) => {
            return Promise.reject(error);
        });

        axios.interceptors.response.use((response: any) => {
            return response;
        }, (error: any) => {
            error = error ? error : { response: {} };
            // tslint:disable-next-line:prefer-const
            let { response: res } = error;
            let { data } = res;

            if (data) {
                if (data.status === 401) {
                    this.doNoLogin(data.data);
                } 
                // else if (data.status === 404) {
                //     this.openErrorPage(404);
                // } else if (data.status === 422) {
                //     this.openErrorPage(422);
                // } else if (data.status === 500) {
                //     this.openErrorPage(500);
                // } else if (data.status === 502) {
                //     this.openErrorPage(502);
                // } else if (data.status === 503) {
                //     this.openErrorPage(503);
                // }
            }

            return Promise.reject(res);
        });
    }

    /**
     * 打开错误页
     *
     * @private
     * @param {number} errorCode
     * @memberof Interceptors
     */
    private openErrorPage(errorCode: number): void {
        window.location.href = `./error/${errorCode}.html`;
    }

    /**
     * 处理未登录异常情况
     *
     * @private
     * @param {*} [data={}]
     * @memberof Interceptors
     */
    private doNoLogin(data: any = {}): void {
        if (data.loginurl && !Object.is(data.loginurl, '') && data.originurl && !Object.is(data.originurl, '')) {
            let _url = encodeURIComponent(encodeURIComponent(window.location.href));
            let loginurl: string = data.loginurl;
            const originurl: string = data.originurl;

            if (originurl.indexOf('?') === -1) {
                _url = `${encodeURIComponent('?RU=')}${_url}`;
            } else {
                _url = `${encodeURIComponent('&RU=')}${_url}`;
            }
            loginurl = `${loginurl}${_url}`;

            window.location.href = loginurl;
        } else {
            if (Object.is(this.router.currentRoute.name, 'login')) {
                return;
            }
            this.router.push({ name: 'login', query: { redirect: this.router.currentRoute.fullPath } });
        }
    }


    /**
     * 构建对象
     * 
     * @memberof Interceptors
     */
    private constructor(router: any) {
        this.router = router;
        this.intercept();
    }

    /**
     * 初始化变量
     *
     * @private
     * @static
     * @type {Interceptors}
     * @memberof Interceptors
     */
    private static interceptors: Interceptors;

    /**
     * 获取单例对象
     *
     * @static
     * @returns {Interceptors}
     * @memberof Interceptors
     */
    public static getInstance(router: any): Interceptors {
        if (!Interceptors.interceptors) {
            Interceptors.interceptors = new Interceptors(router);
        }
        return this.interceptors;
    }
}

